package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX = "cart:uid:";

    /**
     * 添加购物车数据
     * @param cart
     */
    public void addCart(Cart cart) {
        //最终结构 Map<String, Map<String,String>>
        //key
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        //获取当前用户下的购物车
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(key);

        //获取商品id和数量
        String skuId = cart.getSkuId().toString();
        Integer num = cart.getNum();

        //判断当前商品是否已经存在
        Boolean bool = hashOps.hasKey(skuId);
        if (bool != null && bool){
            String jsonCart = hashOps.get(skuId);
            cart = JsonUtils.toBean(jsonCart, Cart.class);
            cart.setNum(cart.getNum() + num);
            hashOps.put(skuId,JsonUtils.toString(cart));
        }
        //存入Redis中
        hashOps.put(skuId,JsonUtils.toString(cart));
    }

    /**
     * 查询购物车列表
     * @return  购物车信息
     */
    public List<Cart> queryCartList() {
        //key
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        //判空
        Boolean bool = stringRedisTemplate.hasKey(key);
        if (bool == null || !bool){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(key);
        Long size = hashOps.size();
        if (size == null || size < 1){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        List<String> carts = hashOps.values();
//        ArrayList<Cart> cartList = new ArrayList<>();
//        for (String c : carts) {
//            Cart cart = JsonUtils.toBean(c, Cart.class);
//            cartList.add(cart);
//        }
        List<Cart> cartList = carts.stream().map(c -> JsonUtils.toBean(c, Cart.class)).collect(Collectors.toList());
        return cartList;
    }
}
